package io.admin.modules.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.admin.common.constant.Constant;
import io.admin.common.page.PageData;
import io.admin.common.service.impl.CrudServiceImpl;
import io.admin.common.utils.ConvertUtils;
import io.admin.common.utils.StringUtils;
import io.admin.modules.sys.dao.ProjectDao;
import io.admin.modules.sys.dao.UserProjectDao;
import io.admin.modules.sys.dto.EquipmentDTO;
import io.admin.modules.sys.dto.FileUrlDTO;
import io.admin.modules.sys.dto.LineDTO;
import io.admin.modules.sys.dto.ProjectCountDTO;
import io.admin.modules.sys.dto.ProjectDTO;
import io.admin.modules.sys.entity.EquipmentEntity;
import io.admin.modules.sys.entity.FileUrlEntity;
import io.admin.modules.sys.entity.LineEntity;
import io.admin.modules.sys.entity.MessageEntity;
import io.admin.modules.sys.entity.ProjectEntity;
import io.admin.modules.sys.entity.ProjectTreeEntity;
import io.admin.modules.sys.entity.UserEntity;
import io.admin.modules.sys.service.EquipmentService;
import io.admin.modules.sys.service.FileUrlService;
import io.admin.modules.sys.service.LineService;
import io.admin.modules.sys.service.MessageService;
import io.admin.modules.sys.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 项目表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-06
 */
@Slf4j
@Service
public class ProjectServiceImpl extends CrudServiceImpl<ProjectDao, ProjectEntity, ProjectDTO> implements ProjectService {

    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private FileUrlService fileUrlService;
    @Autowired
    private LineService LineService;
    @Autowired
    private UserProjectDao userProjectDao;
     @Autowired
     private MessageService messageService;
     @Autowired
     private  ProjectDao projectDao;

    @Override
    public PageData<ProjectDTO> page(Map<String, Object> params) {
        //转换成like
        paramsToLike(params, "projectHead");
        paramsToLike(params, "name");
        //分页
        IPage<ProjectEntity> page = getPage(params, Constant.CREATE_DATE, false);
        //查询
        List<ProjectEntity> list = baseDao.list(params);
        //开始查询用户的信息
        for (ProjectEntity pro:list){
            Map<String,Object> map= new HashMap<>();
            map.put("projectId",pro.getId());
            List<UserEntity> listUser = userProjectDao.getList(map);
            if(!CollectionUtil.isEmpty(listUser)){
              //开始判断当前人员的数据
                //开始统计负责人
                List<String> listProjectHead = listUser.stream().filter(i->i.getUserrole()==2).map(i->i.getUsername()).collect(Collectors.toList());
                if(!CollectionUtil.isEmpty(listProjectHead)){
                    String listProjectHeadStr = listProjectHead.stream().collect(Collectors.joining(","));
                    pro.setProjectHead(listProjectHeadStr);
                }
                pro.setProjectMember(listUser.size());
            }else{
                pro.setProjectMember(0);
            }
        }
        return getPageData(list, page.getTotal(), ProjectDTO.class);
    }

   /* left join  tb_address t4 on t1.provinceId = t4.id
    left join  tb_address t5 on t1.cityId = t5.id
    left join  tb_address t6 on t1.creaId = t6.id*/
    @Override
    public  Set<Map<String,Object>> listProTree(){
        //开始获取当前所有项目数据
        List<ProjectTreeEntity> list = baseDao.listProTree();
        //开始查询用户的信息
        for (ProjectTreeEntity pro:list){
            pro.setLabel(pro.getName());
            Map<String,Object> map= new HashMap<>();
            map.put("projectId",pro.getId());
            List<UserEntity> listUser = userProjectDao.getList(map);
            if(!CollectionUtil.isEmpty(listUser)){
                //开始统计负责人
                List<String> listProjectHead = listUser.stream().filter(i->i.getUserrole()==2).map(i->i.getUsername()).collect(Collectors.toList());
                if(!CollectionUtil.isEmpty(listProjectHead)){
                    String listProjectHeadStr = listProjectHead.stream().collect(Collectors.joining(","));
                    pro.setProjectHead(listProjectHeadStr);
                }
                pro.setProjectMember(listUser.size());
            }else{
                pro.setProjectMember(0);
            }
        }
        if(!CollectionUtil.isEmpty(list)){
            //开始获取对应所有的省绑定
            Set<Map<String,Object>> strProvinceId = list.stream().map( i->{
                        Map<String,Object> map =new HashMap<>();
                        map.put("id",i.getProvinceId());
                        map.put("label",i.getProvinceName());
                        return  map;
            }
            ).collect(Collectors.toSet());
            //开始获取对应所有的市绑定
            Set<Map<String,Object>> strCityId = list.stream().map( i->{
                Map<String,Object> map =new HashMap<>();
                map.put("id",i.getCityId());
                map.put("parentId",i.getProvinceId());
                map.put("label",i.getCityName());
                return  map;
            }).collect(Collectors.toSet());
            //开始获取对应所有的市绑定
            Set<Map<String,Object>> strCreaId = list.stream().map( i->{
                Map<String,Object> map =new HashMap<>();
                map.put("id",i.getCreaId());
                map.put("parentId",i.getCityId());
                map.put("label",i.getCreaName());
                return  map;
            }).collect(Collectors.toSet());
            //开始倒桩数据
            for (Map map:strCreaId){
                List<ProjectTreeEntity> listCreaId = list.stream().filter(i->i.getCreaId().equals(map.get("id"))).collect(Collectors.toList());
                map.put("children",listCreaId);
            }
            //开始倒桩城市
            for (Map map:strCityId){
                 Set<Map<String,Object>>  setCityId = strCreaId.stream().filter(i->i.get("parentId").equals(map.get("id"))).collect(Collectors.toSet());
                 map.put("children",setCityId);
            }
            //开始倒桩省
            for (Map map:strProvinceId){
                Set<Map<String,Object>>  setProvinceId = strCityId.stream().filter(i->i.get("parentId").equals(map.get("id"))).collect(Collectors.toSet());
                map.put("children",setProvinceId);
            }

          return strProvinceId;
        }else{
            return null;
        }
    }





    @Override
    public QueryWrapper<ProjectEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        QueryWrapper<ProjectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
        return wrapper;
    }


    @Override
    public void saveCopyProject(String projectName,String thisProjectId){
       //开始获取当前项目的数据
        //开始查询当前线路信息
        Long copyProjectId =generateRandomLongId();
        ProjectEntity projectEntity = baseDao.selectById(thisProjectId);
        if(null == projectEntity){
            return;
        }
        //开始获取所有的 定点信息
        Map<String,Object> param=new HashMap<String,Object>(1);
        param.put("projectId",String.valueOf(projectEntity.getId()));
        List<LineDTO> listLine = LineService.list(param);
        if(CollectionUtil.isEmpty(listLine)){
            log.info("开始新增项目");
            projectEntity.setId(copyProjectId);
            projectEntity.setName(projectName);
            baseDao.insert(projectEntity);
         return;
        }
        //开始获取线路列表
        List<LineDTO> listCopyLine =new ArrayList<>();
        List<EquipmentDTO> listCopyEquipment =new ArrayList<>();
        List<FileUrlDTO> listCopyFile =new ArrayList<>();
        for(LineDTO lineDto:listLine){
            Long copyLinetId =generateRandomLongId();
            param=new HashMap<String,Object>(1);
            param.put("lineId",String.valueOf(lineDto.getId()));
            List<EquipmentDTO> listEquipment = equipmentService.list(param);
            if(!CollectionUtil.isEmpty(listEquipment)){
                for (EquipmentDTO equipmentDTO:listEquipment){
                    Long copyEquipmentId =generateRandomLongId();
                    param=new HashMap<String,Object>(1);
                    param.put("keysId",String.valueOf(equipmentDTO.getId()));
                    List<FileUrlDTO> listFileUrl = fileUrlService.list(param);
                    if(!CollectionUtil.isEmpty(listFileUrl)){
                        for (FileUrlDTO fileUrlDTO:listFileUrl){
                            fileUrlDTO.setId(generateRandomLongId());
                            fileUrlDTO.setKeysId(copyEquipmentId);
                        }
                        listCopyFile.addAll(listFileUrl);
                    }
                    equipmentDTO.setId(copyEquipmentId);
                    equipmentDTO.setLineId(copyLinetId);
                    equipmentDTO.setProjectId(copyProjectId);
                    listCopyEquipment.add(equipmentDTO);
                }
            }
            lineDto.setId(copyLinetId);
            lineDto.setProjectId(copyProjectId);
            listCopyLine.add(lineDto);
        }

        log.info("开始新增项目");
        projectEntity.setId(copyProjectId);
        projectEntity.setName(projectName);
        projectEntity.setCreateDate(new Date());
        projectEntity.setState(0);
        projectEntity.setExamineState(null);
        baseDao.insert(projectEntity);

        log.info("开始新增定点信息");
        if(!CollectionUtil.isEmpty(listCopyLine)){
            List<LineEntity> lineEntities = ConvertUtils.sourceToTarget(listCopyLine, LineEntity.class);
            LineService.insertBatch(lineEntities);
        }

        log.info("开始新增定点信息");
        if(!CollectionUtil.isEmpty(listCopyEquipment)){
            List<EquipmentEntity> listEquipmentEntity = ConvertUtils.sourceToTarget(listCopyEquipment, EquipmentEntity.class);
            equipmentService.insertBatch(listEquipmentEntity);
        }
        log.info("开始新增图片信息");
        if(!CollectionUtil.isEmpty(listCopyFile)){
            List<FileUrlEntity> listFileUrlEntity = ConvertUtils.sourceToTarget(listCopyFile, FileUrlEntity.class);
            fileUrlService.insertBatch(listFileUrlEntity);
        }
    }
    public static long generateRandomLongId() {
        return ThreadLocalRandom.current().nextLong();
    }
    @Override
    public void updateProjectByMsg(Long projectId,Integer examineState,String projectName,String examineNotes){
        Map<String,Object> map= new HashMap<>();
        map.put("projectId",projectId);
        List<UserEntity> listUser = userProjectDao.getList(map);
        if(!CollectionUtil.isEmpty(listUser)){
            //开始统计负责人
            List<Long> listProjectHead = listUser.stream().filter(i->i.getUserrole()==2).map(i->i.getId()).collect(Collectors.toList());
            //跟据项目状态添加对用户发的消息
            List<MessageEntity> list =new ArrayList<>();
            for (Long userId :listProjectHead){
                MessageEntity msg =new MessageEntity();
                msg.setMsgType(2);
                msg.setKeyIds(projectId);
                msg.setUserId(userId);
                if(examineState.equals(3)){
                    msg.setType(3);
                    msg.setTitle("项目验收驳回");
                    String content ="您提交验收的项目："+projectName +"验收通过驳回";
                    if(!StringUtils.isBlank(examineNotes)){
                        content +="，驳回信息："+examineNotes;
                    }else{
                        content +="。";
                    }
                    msg.setContent(content);
                }
                if(examineState.equals(2)){
                    msg.setType(2);
                    msg.setTitle("项目验收通过");
                    String content ="您提交验收的项目："+projectName +"验收通过";
                    if(!StringUtils.isBlank(examineNotes)){
                        content +="，验收信息："+examineNotes;
                    }else{
                        content +="。";
                    }
                    msg.setContent(content);
                }
                msg.setCreateDate(new Date());
                list.add(msg);
            }
            if(!examineState.equals(1)){
                messageService.insertBatch(list);
            }
        }
    }
    public  ProjectDTO findProByParam(ProjectDTO projectDTO){
      return  projectDao.findProByParam(projectDTO);
    }

   public ProjectCountDTO listProCount (){
       ProjectCountDTO projectCountDTO =new ProjectCountDTO();
       projectCountDTO.setHaveBeenAccepted(baseDao.listProCount("2"));
       projectCountDTO.setUnderConstruction(baseDao.listProCount("0"));
       projectCountDTO.setAcceptanceAgent(baseDao.listProCount("1"));
       return projectCountDTO;
   }
}